<template>
  <el-dialog title="分配权限" :visible="showDialog" @close="closeFn">
    <el-tree
      ref="tree"
      node-key="id"
      check-strictly
      show-checkbox
      default-expand-all
      :data="permList"
      :props="{label:'title'}"
    />
    <template #footer>
      <el-row type="flex" justify="center">
        <el-button type="primary" size="small" @click="submit">确定</el-button>
        <el-button size="small" @click="closeFn">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>
<script>
import { roleDetail, getPermissionList, editRole } from '@/api/roles'
import { listToTree } from '@/utils/index'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      permList: [], // 权限列表
      permissions: [], // 选中的权限数据id
      curRoleId: ''
    }
  },
  async created() {
    const res = await getPermissionList()
    this.permList = listToTree(res.data, '0')
  },
  methods: {
    // 确定 分配权限
    async submit() {
      this.permissions = this.$refs.tree.getCheckedKeys()
      //   调用接口 实现分配权限
      await editRole({
        id: this.curRoleId, // 角色id
        permissions: this.permissions // 权限id集合
      })
      console.log(57, this.permissions)
      //   关闭弹出
      this.closeFn()
    },
    closeFn() {
      this.$emit('update:showDialog', false)
    },
    // 获取角色默认权限数据
    async getRolePermIds(id) {
      this.curRoleId = id
      const res = await roleDetail(id)

      // 保存权限数据
      this.permissions = res.data.permissions
      // 实现回显
      // console.log(this.permissions)
      this.permissions = this.permissions.map(v => {
        return v.id
      })
      console.log(this.permissions)
      this.$refs.tree.setCheckedKeys(this.permissions)
    }
  }
}
</script>
